#include "shoppingcart.h"
#include <QDebug>

ShoppingCart::ShoppingCart(QObject *parent)
    : QObject(parent),
      m_discountRate(1.0),
      m_discountAmount(0.0),
      m_totalAmount(0.0)
{
}

bool ShoppingCart::addProduct(int productId, const QString& productCode,
                             const QString& productName, const QString& specification,
                             double price, int quantity, bool allowDiscount)
{
    // 检查商品是否已在购物车中
    for (auto& item : m_items) {
        if (item.productId == productId) {
            // 商品已存在，增加数量
            item.quantity += quantity;
            item.subtotal = item.price * item.quantity;
            emit quantityUpdated(productId, item.quantity);
            emit cartUpdated();
            return true;
        }
    }

    // 商品不存在，添加新项
    CartItem newItem(productId, productCode, productName, specification,
                    price, quantity, allowDiscount);
    m_items.append(newItem);

    emit itemAdded(newItem);
    emit cartUpdated();
    return true;
}

bool ShoppingCart::removeProduct(int productId)
{
    for (int i = 0; i < m_items.size(); ++i) {
        if (m_items[i].productId == productId) {
            m_items.remove(i);
            emit itemRemoved(productId);
            emit cartUpdated();
            return true;
        }
    }
    return false;
}

bool ShoppingCart::updateQuantity(int productId, int newQuantity)
{
    if (newQuantity <= 0) {
        // 数量为0或负数，移除商品
        return removeProduct(productId);
    }

    for (auto& item : m_items) {
        if (item.productId == productId) {
            item.quantity = newQuantity;
            item.subtotal = item.price * item.quantity;
            emit quantityUpdated(productId, newQuantity);
            emit cartUpdated();
            return true;
        }
    }
    return false;
}

void ShoppingCart::clear()
{
    m_items.clear();
    m_discountRate = 1.0;
    m_discountAmount = 0.0;
    m_totalAmount = 0.0;
    emit cartUpdated();
}

void ShoppingCart::reset()
{
    m_items.clear();
    m_totalAmount = 0.0;
    // 注意：不重置折扣率和折扣金额，因为可能要继续使用相同的会员折扣
    emit cartUpdated();
}

QVector<CartItem> ShoppingCart::getItems() const
{
    return m_items;
}

int ShoppingCart::getItemCount() const
{
    return m_items.size();
}

int ShoppingCart::getTotalQuantity() const
{
    int total = 0;
    for (const auto& item : m_items) {
        total += item.quantity;
    }
    return total;
}

double ShoppingCart::calculateSubtotal() const
{
    double subtotal = 0.0;
    for (const auto& item : m_items) {
        subtotal += item.subtotal;
    }
    return subtotal;
}

/**
 * 应用会员折扣算法
 * 算法说明：
 * 1. 遍历购物车中所有商品，筛选出允许折扣的商品
 * 2. 计算可折扣商品的总金额
 * 3. 根据折扣率计算折扣金额：折扣金额 = 可折扣金额 × (1 - 折扣率)
 * 4. 最终金额 = 商品总金额 - 折扣金额
 * 
 * @param discountRate 折扣率（0.0-1.0，如0.8表示8折）
 * @return 折后总金额
 */
double ShoppingCart::applyDiscount(double discountRate)
{
    m_discountRate = discountRate;
    double subtotal = calculateSubtotal();
    double discountableAmount = 0.0;

    // 计算可折扣金额（只有允许折扣的商品参与）
    for (const auto& item : m_items) {
        if (item.allowDiscount) {
            discountableAmount += item.subtotal;
        }
    }

    // 计算折扣金额
    m_discountAmount = discountableAmount * (1 - discountRate);
    m_totalAmount = subtotal - m_discountAmount;

    return m_totalAmount;
}

void ShoppingCart::setDiscountRate(double rate)
{
    m_discountRate = rate;
    // 重新应用折扣
    applyDiscount(rate);
}

double ShoppingCart::getDiscountRate() const
{
    return m_discountRate;
}

double ShoppingCart::getTotal() const
{
    return m_totalAmount;
}

double ShoppingCart::getDiscountAmount() const
{
    return m_discountAmount;
}

bool ShoppingCart::isEmpty() const
{
    return m_items.isEmpty();
}

CartItem ShoppingCart::findItem(int productId) const
{
    for (const auto& item : m_items) {
        if (item.productId == productId) {
            return item;
        }
    }
    return CartItem();
}

CartItem ShoppingCart::findItemByCode(const QString& productCode) const
{
    for (const auto& item : m_items) {
        if (item.productCode == productCode) {
            return item;
        }
    }
    return CartItem();
}

QVector<OrderDetail> ShoppingCart::toOrderDetails() const
{
    QVector<OrderDetail> details;

    for (const auto& item : m_items) {
        OrderDetail detail;
        detail.productId = item.productId;
        detail.quantity = item.quantity;
        detail.unitPrice = item.price;
        detail.subtotal = item.subtotal;
        detail.isDiscounted = item.allowDiscount && m_discountRate < 1.0;

        details.append(detail);
    }

    return details;
}

CartSummary ShoppingCart::getSummary() const
{
    CartSummary summary;
    summary.itemCount = getItemCount();
    summary.totalQuantity = getTotalQuantity();
    summary.subtotal = calculateSubtotal();
    summary.discount = getDiscountAmount();
    summary.total = getTotal();

    return summary;
}
